import { history } from 'umi'
import { Tabs } from 'antd-mobile'
import { fetchCourseDetail } from '../api'
import { CourseIntro, CourseList } from './components'
import { useEffect, useState, useRef, useLayoutEffect } from 'react'
import Player from 'xgplayer'
import styles from './index.module.less'
import type { CourseDetail, Lesson } from './interface'

export const OnlineClassDetail = () => {
    // 播放器高度（单位px）
    const PLAYER_HEIGHT_PX = 421

    const historyQuery = history.location.query as { id: string; lessonId: string }
    const id = Number(historyQuery.id)
    const lessonId = Number(historyQuery.lessonId ?? 0)

    const [sourceUrl, setSourceUrl] = useState<string>()
    const [detailData, setDetailData] = useState<CourseDetail>()

    const player = useRef<Player>()

    useLayoutEffect(() => {
        player.current = new Player({
            id: 'course',
            url: '',
            width: '100%',
            height: `${(PLAYER_HEIGHT_PX / 750) * 100}vw`,
            fitVideoSize: 'auto',
        })
    }, [])

    /** 获取默认章节属性（第一节） */
    const getDefaultLesson = (field?: keyof Lesson) => {
        if (!detailData) return
        const defaultLesson = detailData.lessons[0]
        return field ? defaultLesson[field] : defaultLesson
    }

    useEffect(() => {
        const initData = async () => {
            const data = await fetchCourseDetail(id)
            setDetailData(data)
        }
        initData()
    }, [id])

    useEffect(() => {
        if (!detailData) return
        let defaultLesson: Lesson | undefined
        if (lessonId) {
            defaultLesson = detailData?.lessons.find(item => Number(item.lessonId) === lessonId)
        } else {
            defaultLesson = detailData?.lessons[0]
        }
        setSourceUrl(defaultLesson?.url)
    }, [lessonId, detailData])

    useEffect(() => {
        if (!sourceUrl) return
        if (!player.current) return
        try {
            if (!player.current.hasStart) {
                player.current.start(sourceUrl)
                return
            }
            player.current.src = sourceUrl
            player.current.play()
        } catch (err) {
            console.log('🐞 => useEffect => err', err)
        }
    }, [sourceUrl, player])

    return (
        <div className={styles.page}>
            <div id="course" className={styles.player} />
            <Tabs>
                <Tabs.Tab title="目录" key="list">
                    <CourseList
                        currentLesson={lessonId || Number(getDefaultLesson('lessonId'))}
                        lessons={detailData?.lessons}
                    />
                </Tabs.Tab>
                <Tabs.Tab title="简介" key="intro">
                    <CourseIntro content={detailData?.content} />
                </Tabs.Tab>
            </Tabs>
        </div>
    )
}

export default OnlineClassDetail
